// pages/volunteer/newappointment/newappointment.js

import requestUtil from "../../../api/request"
import API from "../../../api/http.api"
const app = getApp()
const audioPlayer = wx.createInnerAudioContext();

Page({

    /**
     * 页面的初始数据
     */
    data: {
        nextPage: 1,
        pageSize: 10,
        isSlider: false,
        disablethisPage: false,
        // 使用 object 存储
        appointment_list: {},
        // 当前正在播放的音频的id
        currentPlayingAudioId: null
        // appointment_list: [],
        // appointment_list: {
        //     "oE_Hx5O2J8-tgl6eWV6bAZtFuCOU#####1595557481318": {
        //         "msg_state": 0,
        //         "createTime": "2020/7/24 上午12:55:41",
        //         "fromUserOpenId": "oE_Hx5O2J8-tgl6eWV6bAZtFuCOU",
        //         "msgType": "audio",
        //         "id": "oE_Hx5O2J8-tgl6eWV6bAZtFuCOU#####1595557481318",
        //         "content": "oE_Hx5O2J8-tgl6eWV6bAZtFuCOU#####1595557480985.mp3",
        //         "fromUserAvatarUrl": "https://wx.qlogo.cn/mmopen/vi_32/kIibIibympndr7rFIIicC3HNPRBCruWr7WoicAr2yBI7DibtLIFo5YibhvyyfIg7wBo070TCzaM5ybRve489Jl5ycq1g/132",
        //         "fromUserNickName": "E.T.",
        //         "playing": false
        //     },
        //     "oE_Hx5O2J8-tgl6eWV6bAZtFuCOU#####1595557481319": {
        //         "msg_state": 0,
        //         "createTime": "2020/7/24 上午10:24:00",
        //         "fromUserOpenId": "oE_Hx5O2J8-tgl6eWV6bAZtFuCOU",
        //         "msgType": "audio",
        //         "id": "oE_Hx5O2J8-tgl6eWV6bAZtFuCOU#####1595557481319",
        //         "content": "oE_Hx5O2J8-tgl6eWV6bAZtFuCOU#####1595557480985.mp3",
        //         "fromUserAvatarUrl": "https://wx.qlogo.cn/mmopen/vi_32/kIibIibympndr7rFIIicC3HNPRBCruWr7WoicAr2yBI7DibtLIFo5YibhvyyfIg7wBo070TCzaM5ybRve489Jl5ycq1g/132",
        //         "fromUserNickName": "E.T.......",
        //         "playing": false
        //     }
        // }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        console.log("onLoad")


        audioPlayer.onPlay(() => {
            console.log("播放开始")
            // 用来跳过第一次
            var i = 0
            var appointment_list = this.data.appointment_list

            console.log(this.data.currentPlayingAudioId)

            // 获取当前播放音频的总时长
            var duration = Math.ceil(appointment_list[this.data.currentPlayingAudioId].duration / 1000)
            // 获取播放到的位置，调整进度条
            this.data.audioPercentageInterval = setInterval(() => {
                // var currentTime = Math.ceil(audioPlayer.currentTime)

                var currentTime = audioPlayer.currentTime
                if (i > 0) {
                    // console.log("currentTime:" + currentTime)
                    // 计算进度条的值
                    appointment_list[this.data.currentPlayingAudioId].audioPercentage = Math.ceil(100 * currentTime / duration)

                    // 计算 showTime1
                    currentTime = Math.ceil(currentTime)
                    var min = parseInt(currentTime / 60);
                    var sec = parseInt(currentTime % 60);
                    if (min.toString().length == 1) {
                        min = `0${min}`;
                    }
                    if (sec.toString().length == 1) {
                        sec = `0${sec}`;
                    }
                    appointment_list[this.data.currentPlayingAudioId].showTime1 = `${min}:${sec}`
                    this.setData({
                        appointment_list: appointment_list
                    })
                }
                i = i + 1
            }, 250);
        })

        // 调用 audioPlayer.stop() 后触发 
        audioPlayer.onStop(() => {
            console.log("手动终止，播放结束")
            var appointment_list = this.data.appointment_list

            // 清除正在播放音频的计时器
            clearInterval(this.data.audioPercentageInterval)

            // 重置播放状态，如果是拖动后的stop则不重置
            if (this.data.isSlider == true) {
                this.data.isSlider = false
            } else {
                appointment_list[this.data.currentPlayingAudioId].playing = false
                this.setData({
                    currentPlayingAudioId: null,
                    appointment_list: appointment_list
                })
            }
        })

        // 自然播放完后触发
        audioPlayer.onEnded(() => {
            console.log("自然播放结束")
            // 清除计时器
            clearInterval(this.data.audioPercentageInterval)

            // 重置刚刚播放完的音频
            var appointment_list = this.data.appointment_list

            console.log(appointment_list)
            console.log(this.data.currentPlayingAudioId)

            // 重置播放状态
            appointment_list[this.data.currentPlayingAudioId].playing = false
            // 重置进度条
            appointment_list[this.data.currentPlayingAudioId].audioPercentage = 0
            // 重置时间进度
            appointment_list[this.data.currentPlayingAudioId].showTime1 = "00:00"
            this.setData({
                // 将当前正在播放的音频 Id 设为 null
                currentPlayingAudioId: null,
                appointment_list: appointment_list
            })
        })

        audioPlayer.onError((error) => {
            console.log(error)
        })
    },

    // 加载数据，下拉刷新，上滑自动加载都依靠此函数
    loadPageData: function() {
        console.log("nextPage：" + this.data.nextPage)
        console.log("pageCount：" + this.data.pageCount)

        requestUtil.post(API.UNTREATED_APPOINTMENT_LIST, {
            "currentPage": this.data.nextPage,
            "pageSize": this.data.pageSize
        }).then(res => {
            console.log(res)
            var list = res.data.list
            var nextPage = this.data.nextPage + 1
            // var appointment_list = this.data.onPullDownRefresh == true ? [] : this.data.appointment_list
            var appointment_list = this.data.onPullDownRefresh == true ? {} : this.data.appointment_list
            list.forEach((value, index) => {

                value["playing"] = false
                value["showTime1"] = "00:00"
                value["audioPercentage"] = 0
                value["content"] = API.FILE_DOWNLOAD + "?fileName=" + value["content"] + "&sessionId=" + app.globalData.sessionId + "&openId=" + app.globalData.openId + "&fileProp="+API.fILE_PROP_APPOINTMENT
                var duration = Math.ceil(value.duration / 1000)
                var min = parseInt(duration / 60);
                var sec = parseInt(duration % 60);
                if (min.toString().length == 1) {
                    min = `0${min}`;
                }
                if (sec.toString().length == 1) {
                    sec = `0${sec}`;
                }
                value["showTime2"] = `${min}:${sec}`

                var id = value["id"]
                // appointment_list.push(value)
                appointment_list[id] = value
            })
            console.log(appointment_list)
            if (this.data.onPullDownRefresh == true) {
                wx.showToast({
                    title: '刷新成功',
                    icon: "success"
                })
                wx.stopPullDownRefresh()
            }
            this.setData({
                appointment_list: appointment_list,
                nextPage: nextPage,
                pageCount: res.data.pageCount,
                onPullDownRefresh: false
            })

        }).catch(err => {
            wx.showToast({
                title: '请下拉刷新重试',
                icon: "none"
            })
        })
    },

    // 播放按钮
    playAudio: function(e) {
        var that = this
        // 获取 key
        var key = e.target.dataset.key
        // 获取播放信息
        var targetInfo = this.data.appointment_list[key]
        var appointment_list = this.data.appointment_list
        console.log(targetInfo)
        console.log(appointment_list)

        // 先判断有没有正在播放的音频，有则关闭
        if (this.data.currentPlayingAudioId != null) {
            console.log("停止正在播放的音频")
            // 停止正在播放的音频
            audioPlayer.stop()
            // 清除正在播放音频的计时器
            clearInterval(this.data.audioPercentageInterval)
            appointment_list[this.data.currentPlayingAudioId].playing = false
        }

        console.log(targetInfo.content)

        audioPlayer.src = targetInfo.content
        setTimeout(() => {
            console.log(key)
            console.log(targetInfo)

            // audioPlayer.autoplay = true

            // 判断进度条位置
            console.log(targetInfo.audioPercentage)
            if (targetInfo.audioPercentage != 0) {
                console.log("跳跃播放")
                var duration = Math.ceil(targetInfo.duration / 1000)
                // 计算要跳跃到的位置
                var seek = Math.floor(duration / 100 * targetInfo.audioPercentage)
                audioPlayer.seek(seek)
            }

            appointment_list[key].playing = true
            that.setData({
                currentPlayingAudioId: key,
                appointment_list: appointment_list
            })
            setTimeout(() => {
                audioPlayer.play()
            }, 100)
        }, 200)

    },

    // 暂停按钮
    pauseAudio: function(e) {
        // var key = e.target.dataset.key
        // var appointment_list = this.data.appointment_list

        // 停止正在播放的音频
        audioPlayer.stop()
        // 清除正在播放音频的计时器
        clearInterval(this.data.audioPercentageInterval)
        // 重置播放状态
        // appointment_list[key].playing = false
        // this.setData({
        //     currentPlayingAudioId: null,
        //     appointment_list: appointment_list
        // })
    },

    // silder 滑块拖动停止后触发，要处理正在播放和没播放两种情况
    sliderChange: function(e) {
        console.log(e)
        console.log("拖动结束")
        var value = e.detail.value
        var key = e.target.dataset.key
        var appointment_list = this.data.appointment_list
        // 判断当前音频是否在播放
        if (key == this.data.currentPlayingAudioId) {
            // 当前音频在播放
            var duration = Math.ceil(this.data.appointment_list[this.data.currentPlayingAudioId].duration / 1000)
            // 计算要跳跃到的位置
            var seek = Math.floor(duration / 100 * value)

            this.data.isSlider = true

            // 停止
            audioPlayer.stop()
            // 跳转
            audioPlayer.seek(seek)
            // 播放
            setTimeout(() => {
                audioPlayer.play()
            }, 100)
        } else {
            // 当前音频没在播放

            appointment_list[key].audioPercentage = value
            this.setData({
                appointment_list: appointment_list
            })
        }
    },

    // silder 滑块拖动时触发，要处理正在播放和没播放两种情况
    sliderChanging: function(e) {
        // 判断当前音频是否在播放
        if (e.target.dataset.key == this.data.currentPlayingAudioId) {
            // 在播放则停止计时器
            console.log("当前拖动的音频正在播放，停止计时器")
            clearInterval(this.data.audioPercentageInterval)
        }
    },

    // 帮助按钮
    helpThisOne: function(e) {
        audioPlayer.stop()
        console.log(e.target.dataset.key)
        var that = this
        var key = e.target.dataset.key
        var appointment_list = this.data.appointment_list
        wx.showModal({
            title: '提示',
            content: '您确定要接受此预约吗，请量力而行，一旦接受不可取消',
            // showCancel: false,
            confirmText: '确定',
            success: function(res) {
                if (res.confirm) {
                    audioPlayer.stop()
                    requestUtil.post(API.HANDLE_APPOINTMENT, {
                        appointmentId: key,
                        // handleUserOpenId: app.globalData.openId
                    }).then(res => {
                        wx.showToast({
                            title: res.message,
                            icon: "none",
                            duration: 2000,
                            complete: function() {
                                delete(appointment_list[key])
                                that.setData({
                                    appointment_list: appointment_list,
                                    disablethisPage: true
                                })
                                app.globalData.disableHell = true
                            }
                        })
                    }).catch(err => {
                        wx.showToast({
                            title: "操作失败，该预约已被其它人接受，请下拉刷新",
                            icon: "none",
                            complete: function() {
                                delete(appointment_list[key])
                                that.setData({
                                    appointment_list: appointment_list
                                })
                            }
                        })
                    })
                }
            }
        })

    },

    // 收到消息
    // onMessage: function(data) {
    //     var that = this
    //     console.log("newappointment 页收到如下消息")
    //     console.log(data)
    //     var msg = JSON.parse(data.data)
    //     console.log(msg)
    //     if (msg.message_property == 'videoCall') {
    //         const callId = msg.data.id
    //         const roomID = msg.data.roomId
    //         console.log(callId)
    //         console.log(roomID)
    //         wx.showModal({
    //             title: "实时求助",
    //             content: "当前有人发起了一个音视频求助，立即帮助他/她吧？",
    //             cancelText: "忽略",
    //             confirmText: "帮助",
    //             success: function(res) {
    //                 if (res.confirm) {
    //                     console.log("点击了确定")
    //                     requestUtil.post(API.HANDLE_VIDEO_CALL, {
    //                         "callId": callId
    //                     }).then((res) => {
    //                         console.log(res)
    //                         app.globalData.userSig = res.data.userSig
    //                         console.log(app.globalData.userSig)
    //                         const url = `../../room/room?userID=${app.globalData.openId}&callId=${callId}&roomID=${roomID}&cloudenv=PRO&frontCamera=front`
    //                         that.checkDeviceAuthorize().then((result) => {
    //                             console.log('授权成功', result)
    //                             wx.navigateTo({ url: url })
    //                         }).catch((error) => {
    //                             console.log('没有授权', error)
    //                         })
    //                     }).catch((err) => {
    //                         wx.showToast({
    //                           title: '抱歉，已经有小伙伴赶在您前面了',
    //                           icon:'none',
    //                           duration:3000
    //                         })
    //                     })
    //                 }
    //             }
    //         })
    //     }
    // },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {
        console.log("onShow")
        this.checkIfDisableHelp()

        // 判断是否需要加载第一页
        if (this.data.disablethisPage == false && this.data.nextPage == 1) {
            this.loadPageData()
        }

        if (this.data.currentPlayingAudioId != null) {
            // 重置播放状态
            appointment_list[this.data.currentPlayingAudioId].playing = false
            // 重置进度条
            appointment_list[this.data.currentPlayingAudioId].audioPercentage = 0
            // 重置时间进度
            appointment_list[this.data.currentPlayingAudioId].showTime1 = "00:00"
            this.setData({
                // 将当前正在播放的音频 Id 设为 null
                currentPlayingAudioId: null,
                appointment_list: appointment_list
            })
        }
    },

    /**
     * 检查是否需要禁用帮助按钮
     */
    checkIfDisableHelp: function() {
        if (app.globalData.disableHell == true) {
            this.setData({
                disablethisPage: true
            })
        } else {
            this.setData({
                disablethisPage: false
            })
        }
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {
        audioPlayer.pause()
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {
        audioPlayer.stop()
        audioPlayer.destroy()
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {
        if (this.data.disablethisPage == true) {
            wx.stopPullDownRefresh()
            return
        }

        console.log("下拉刷新")
        // 停止音频播放
        audioPlayer.stop()
        // 清除播放信息
        this.data.nextPage = 1
        this.setData({
            currentPlayingAudioId: null,
            onPullDownRefresh: true,
            // nextPage: 1
        })
        this.loadPageData()
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {
        if (this.data.nextPage <= this.data.pageCount) {
            console.log("加载更多数据中。。。")
            this.loadPageData()
        } else {
            console.log("没有更多数据")
        }
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function() {

    },

    checkDeviceAuthorize: function() {
        this.hasOpenDeviceAuthorizeModal = false
        return new Promise((resolve, reject) => {
            if (!wx.getSetting || !wx.getSetting()) {
                // 微信测试版 获取授权API异常，目前只能即使没授权也可以通过
                resolve()
            }
            wx.getSetting().then((result) => {
                console.log('getSetting', result)
                this.authorizeMic = result.authSetting['scope.record']
                this.authorizeCamera = result.authSetting['scope.camera']
                if (result.authSetting['scope.camera'] && result.authSetting['scope.record']) {
                    // 授权成功
                    resolve()
                } else {
                    // 没有授权，弹出授权窗口
                    // 注意： wx.authorize 只有首次调用会弹框，之后调用只返回结果，如果没有授权需要自行弹框提示处理
                    console.log('getSetting 没有授权，弹出授权窗口', result)
                    wx.authorize({
                        scope: 'scope.record',
                    }).then((res) => {
                        console.log('authorize mic', res)
                        this.authorizeMic = true
                        if (this.authorizeCamera) {
                            resolve()
                        }
                    }).catch((error) => {
                        console.log('authorize mic error', error)
                        this.authorizeMic = false
                    })
                    wx.authorize({
                        scope: 'scope.camera',
                    }).then((res) => {
                        console.log('authorize camera', res)
                        this.authorizeCamera = true
                        if (this.authorizeMic) {
                            resolve()
                        } else {
                            this.openConfirm()
                            reject(new Error('authorize fail'))
                        }
                    }).catch((error) => {
                        console.log('authorize camera error', error)
                        this.authorizeCamera = false
                        this.openConfirm()
                        reject(new Error('authorize fail'))
                    })
                }
            })
        })
    },
    openConfirm: function() {
        if (this.hasOpenDeviceAuthorizeModal) {
            return
        }
        this.hasOpenDeviceAuthorizeModal = true
        return wx.showModal({
            content: '您没有打开麦克风和摄像头的权限，是否去设置打开？',
            confirmText: '确认',
            cancelText: '取消',
            success: (res) => {
                this.hasOpenDeviceAuthorizeModal = false
                console.log(res)
                // 点击“确认”时打开设置页面
                if (res.confirm) {
                    console.log('用户点击确认')
                    wx.openSetting({
                        success: (res) => {},
                    })
                } else {
                    console.log('用户点击取消')
                }
            },
        })
    },
})